﻿using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using BabyShop.WebSite.ViewModels;

namespace BabyShop.WebSite.Areas.SysManage.Controllers
{
    public class PhotoController : BaseController
    {
        [HttpPost]
        public ActionResult Upload(UploadViewModel uploadViewModel)
        {
            string disposition = Request.ServerVariables["HTTP_CONTENT_DISPOSITION"];
            byte[] fileBytes;
            string originalFileName = string.Empty;
            string err = String.Empty, msg = string.Empty;
            if(!string.IsNullOrEmpty(disposition)) {
                fileBytes = Request.BinaryRead(Request.TotalBytes);
                originalFileName = Regex.Match(disposition, @"filename=""(.+?)""").Groups[1].Value;
            }
            else {
                var postedFile = Request.Files.Get(uploadViewModel.InputName);
                if (postedFile != null) {
                    originalFileName = postedFile.FileName;
                    fileBytes = new byte[postedFile.ContentLength];
                    using (Stream stream = postedFile.InputStream) {
                        stream.Read(fileBytes, 0, postedFile.ContentLength);
                        stream.Close();
                    }
                }
                else
                    fileBytes = new byte[0];
            }
            if (fileBytes.Length == 0)
                err = "无数据提交";
            else {
                string fileExtName = Path.GetExtension(originalFileName);
                fileExtName = fileExtName == null ? string.Empty : fileExtName.ToLower();
                if (!uploadViewModel.UpExt.Contains(fileExtName.Replace(".", string.Empty)))
                    err = "上传文件扩展名必需为：" + uploadViewModel.UpExt;
                else {
                    string attachSubDir;
                    switch (uploadViewModel.DirType) {
                        case 2:
                            attachSubDir = "month_" + DateTime.Now.ToString("yyMM");
                            break;
                        case 3:
                            attachSubDir = "ext_" + fileExtName;
                            break;
                        default:
                            attachSubDir = "day_" + DateTime.Now.ToString("yyMMdd");
                            break;
                    }
                    string attachDir = string.Format("/{0}/{1}/", uploadViewModel.AttachDir, attachSubDir);
                    string attachDirFullPath = Server.MapPath("~" + attachDir);
                    long tempFileName = DateTime.Now.Ticks;
                    string fileFullPath = string.Format("{0}{1}{2}", attachDirFullPath, tempFileName, fileExtName);
                    string returnFilePath = string.Format("{0}{1}{2}", attachDir, tempFileName, fileExtName);
                    try {
                        if (!Directory.Exists(attachDirFullPath))
                            Directory.CreateDirectory(attachDirFullPath);
                        System.IO.File.WriteAllBytes(fileFullPath, fileBytes);
                    }
                    catch (Exception ex) {
                        err = ex.Message;
                    }
                    if(uploadViewModel.Immediate == 1)
                        msg = "!" + returnFilePath;
                }
            }
            return uploadViewModel.MsgType == 1
                       ? Json(new {err, msg})
                       : Json(new {err, msg = new {url = msg, localname = originalFileName, id = 1}});
        }
    }
}
